import { serviceContext } from '@/service/context'
import produce from 'immer'
import { Dispatch } from 'redux'
import { E_A_AUTH_TYPE } from '../action-types'
import { IAction } from '../store-types'
import { createAction } from '../store-util'

export interface IAuthState {
  isLoggedIn: Boolean
  token: string
  userId: number
}

const initialState: IAuthState = {
  isLoggedIn: true,
  token: '',
  userId: 0
}

export interface IAuthAction {
  setIsLoggedIn(isLoggedIn: boolean): void
  setToken(token: string): void
  setUserId(userId: number): void
}

export const setIsLoggedIn = (isLoggedIn: boolean) => (dispatch: Dispatch) => {
  dispatch(createAction(E_A_AUTH_TYPE.SET_IS_LOGGED_IN, isLoggedIn))
}

export const setToken = (token: string) => (dispatch: Dispatch) => {
  dispatch(createAction(E_A_AUTH_TYPE.SET_TOKEN, token))
}

export const setUserId = (userId: number) => (dispatch: Dispatch) => {
  dispatch(createAction(E_A_AUTH_TYPE.SET_USER_ID, userId))
}

export default function reducer(state: IAuthState = initialState, action: IAction) {
  switch (action.type) {
    case E_A_AUTH_TYPE.SET_IS_LOGGED_IN:
      return produce(state, draft => {
        draft.isLoggedIn = action.payload as boolean
      })
    case E_A_AUTH_TYPE.SET_TOKEN:
      return produce(state, draft => {
        const token = action.payload as string
        serviceContext.get().http.setToken(token)
        draft.token = token
      })
    case E_A_AUTH_TYPE.SET_USER_ID:
      return produce(state, draft => {
        const userId = action.payload as number
        serviceContext.get().dataManager.currentUserId = userId
        draft.userId = userId
      })
    default:
      return state
  }
}

declare module '../store-types' {
  interface IGlobalState {
    auth: IAuthState
  }
}
